package com.wanyangproject.my;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.wanyangproject.R;
import com.wanyangproject.entity.PhotoEntity;
import com.wanyangproject.entity.UserEntity;
import com.wanyangproject.entity.XiuGaiEntity;
import com.wanyangproject.popuwindow.BirthdayPopupWindow;
import com.wanyangproject.popuwindow.TakePhotoPopWin;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.GlideCircleTransform;
import com.wanyangproject.utils.GlideImageLoaderForPicker;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


public class WoDeZiLiaoActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.tv_xingming)
    TextView tvXingming;
    @BindView(R.id.tv_card)
    TextView tvCard;
    private TakePhotoPopWin takePhotoPopWin;
    private BirthdayPopupWindow birthdayPopupWindow;
    private UserEntity userEntity;
    private String sex = "0";
    private PhotoEntity photoEntity;
    private String string = "";//时间戳
    private Uri photoUri;
    private ImageView image_touxiang;
    private ImageView imageBack;
    private EditText etName;
    private ImageView imageNan;
    private ImageView imageNv;
    private TextView tvXuanzeShengri;
    private Button btnSave;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wo_de_zi_liao);
        ButterKnife.bind(this);

        image_touxiang = (ImageView) findViewById(R.id.image_touxiang);
        imageBack = (ImageView) findViewById(R.id.image_back);
        etName = (EditText) findViewById(R.id.et_name);
        imageNan = (ImageView) findViewById(R.id.image_nan);
        imageNv = (ImageView) findViewById(R.id.image_nv);
        tvXuanzeShengri = (TextView) findViewById(R.id.tv_xuanze_shengri);
        btnSave = (Button) findViewById(R.id.btn_save);

        imageBack.setOnClickListener(this);
        image_touxiang.setOnClickListener(this);
        etName.setOnClickListener(this);
        imageNan.setOnClickListener(this);
        imageNv.setOnClickListener(this);
        tvXuanzeShengri.setOnClickListener(this);
        btnSave.setOnClickListener(this);



        //  获取用户信息的网络请求
        initYongHuXinXiHttp();


    }


    //    获取用户信息的网络请求
    private void initYongHuXinXiHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "Life/user")
                .addHeader("token", ContractUtils.getTOKEN(WoDeZiLiaoActivity.this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e + "       eeee用户信息");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(WoDeZiLiaoActivity.this, response);
                        System.out.println(response + "    获取个人用户信息的网络请求修改资料页面");
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            userEntity = gson.fromJson(response, UserEntity.class);
                            if (userEntity != null) {
                                UserEntity.ResponseBean responseBean = userEntity.getResponse();
                                if (responseBean != null) {
                                    etName.setText(responseBean.getNickname() != null ? responseBean.getNickname() : "");
                                    if (responseBean.getSex() != null) {
                                        sex = responseBean.getSex();
                                        if (responseBean.getSex().equals("0")) {
                                            imageNan.setImageResource(R.drawable.checked);
                                            imageNv.setImageResource(R.drawable.unchecked);
                                        } else {
                                            imageNv.setImageResource(R.drawable.checked);
                                            imageNan.setImageResource(R.drawable.unchecked);
                                        }

                                        tvXuanzeShengri.setText(stampToDate(responseBean.getBirth()));
                                        setHeadImage(responseBean.getAvatar());
                                    }

                                    if(responseBean.getIdCard().equals("")){
                                        tvCard.setVisibility(View.GONE);
                                    }else {
                                        tvCard.setVisibility(View.VISIBLE);
                                        String idCard = responseBean.getIdCard();
                                        String s = idCard.substring(0, 4) + "**********" + idCard.substring(14);
                                        System.out.println(s+"     sssssssssssss");
                                        tvCard.setText("身份证号："+s);
                                    }



                                    if(responseBean.getRealname().equals("")){
                                        tvXingming.setVisibility(View.GONE);
                                    }else {
                                        tvXingming.setVisibility(View.VISIBLE);
                                        tvXingming.setText("姓名：   "+responseBean.getRealname());
                                    }
                                }
                            }
//                            Intent intent=new Intent();
//                            intent.putExtra("touxiang",userEntity.getResponse().getAvatar());
//                            intent.putExtra("name",userEntity.getResponse().getNickname());
//                            intent.putExtra("sex",userEntity.getResponse().getSex());
//                            intent.putExtra("shengri",userEntity.getResponse().getAge());
//                            intent.setAction("xiugai");
//                            sendBroadcast(intent);
                        }
                    }
                });
    }



    private void setHeadImage(String avatar) {
        if (avatar != null && image_touxiang != null) {
            Glide.with(WoDeZiLiaoActivity.this)
                    .load(avatar)
                    .transform(new GlideCircleTransform(WoDeZiLiaoActivity.this))
                    .into(image_touxiang);
        }
    }


    /*
    * 将时间戳转换为时间
    */
    public String stampToDate(String s) {
        if (s == null) {
            return "";
        }

        if (s.length() == 0) {
            return "";
        }

        if (s.indexOf("-") != -1) {
            return "";
        }
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long lt = new Long(s);
        Date date = new Date(lt * 1000);
        res = simpleDateFormat.format(date);
        return res;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            返回按钮
            case R.id.image_back:
                finish();
                break;
//            头像
            case R.id.image_touxiang:
                Object itemsOnClick = null;
                takePhotoPopWin = new TakePhotoPopWin(WoDeZiLiaoActivity.this, (View.OnClickListener) itemsOnClick);
                takePhotoPopWin.showAtLocation(findViewById(R.id.relative_ziliao), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                takePhotoPopWin.setOnClickXiangji(new TakePhotoPopWin.OnClickXiangji() {
                    @Override
                    public void onClick(int id) {
//                        Intent open = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                        startActivityForResult(open,100);

                        //                判断当前SDK版本号
                        if (Build.VERSION.SDK_INT >= 23) {
//                    当前拨打电话权限是没有给的
                            if (ContextCompat.checkSelfPermission(WoDeZiLiaoActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                        我要请求权限
                                ActivityCompat.requestPermissions(WoDeZiLiaoActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                            } else {
                                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                                    //创建文件夹 在本地文件Pictures 目录下创建 自己得文件夹
                                    File dir = new File(Environment.getExternalStorageDirectory() + "/Pictures/image");
                                    if (!dir.exists()) {
                                        dir.mkdirs();
                                    }
                                    //照片名称
                                    File file = new File(dir, new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
                                    photoUri = Uri.parse(file.getPath());

                                    startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                                            .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), 100);

                                } else {
//                                    showToast("请检查SDCard！");
                                }
                            }
                        } else {
                            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                                //创建文件夹 在本地文件Pictures 目录下创建 自己得文件夹
                                File dir = new File(Environment.getExternalStorageDirectory() + "/Pictures/image");
                                if (!dir.exists()) {
                                    dir.mkdirs();
                                }
                                //照片名称
                                File file = new File(dir, new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
                                photoUri = Uri.parse(file.getPath());

                                startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                                        .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), 100);

                            } else {
//                                    showToast("请检查SDCard！");
                            }
                        }
                    }
                });


                //                点击相册
                takePhotoPopWin.setOnClickXiangce(new TakePhotoPopWin.OnClickXiangce() {
                    @Override
                    public void onClick(int id) {

                        ImagePicker imagePicker = ImagePicker.getInstance();
                        imagePicker.setImageLoader(new GlideImageLoaderForPicker());   //设置图片加载器
                        imagePicker.setShowCamera(true);  //显示拍照按钮
                        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
                        imagePicker.setSaveRectangle(true);//是否按矩形区域保存
                        imagePicker.setFocusHeight(169);
                        imagePicker.setFocusWidth(169);
                        imagePicker.setCrop(false);
                        imagePicker.setSelectLimit(1);    //选中数量限制
                        imagePicker.setOutPutX(800);//保存文件的宽度。单位像素
                        imagePicker.setOutPutY(800);//保存文件的高度。单位像素

                        Intent intent = new Intent(WoDeZiLiaoActivity.this, ImageGridActivity.class);
                        startActivityForResult(intent, 1);
                    }
                });
                break;
//            、昵称
            case R.id.et_name:
                break;
//            男
            case R.id.image_nan:
                sex = "0";
                imageNan.setImageResource(R.drawable.checked);
                imageNv.setImageResource(R.drawable.unchecked);
                break;
//            女
            case R.id.image_nv:
                sex = "1";
                imageNv.setImageResource(R.drawable.checked);
                imageNan.setImageResource(R.drawable.unchecked);
                break;
//            选择生日
            case R.id.tv_xuanze_shengri:
                Calendar calendar = Calendar.getInstance();

                TimePickerView timePickerView = new TimePickerView.Builder(WoDeZiLiaoActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                        tvXuanzeShengri.setText(simpleDateFormat1.format(date));


//                        try {
//                            date = simpleDateFormat1.parse(tvXuanzeShengri.getText().toString());
//                            long time = date.getTime();
//                            string = String.valueOf(time/1000);
//                            System.out.println(string + "     时间戳");
//                        } catch (ParseException e) {
//                            e.printStackTrace();
//                        }
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setTextXOffset(0, 0, 0, 0, 0, 0)
                        .setLunarCalendar(false)
//                        .setContentSize(20)//滚轮文字大小
                        .gravity(Gravity.CENTER)
                        .setTitleSize(16)//标题文字大小
                        .setTitleText("请选择时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(false)//是否循环滚动
                        .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                        .setTextColorOut(Color.parseColor("#AEAAAA"))
                        .setTitleColor(Color.BLACK)//标题文字颜色
                        .setSubmitColor(Color.RED)//确定按钮文字颜色
                        .setCancelColor(Color.parseColor("#AEAAAA"))//取消按钮文字颜色
                        .setTitleBgColor(Color.parseColor("#f5f5f5"))//标题背景颜色 Night mode
                        .setBgColor(Color.parseColor("#ffffff"))//滚轮背景颜色 Night mode
                        .setRange(1900, calendar.get(Calendar.YEAR))//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
                        .setLabel("年", "月", "日", ":", "", "")
                        .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .isDialog(false)//是否显示为对话框样式
                        .build();
                timePickerView.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                timePickerView.show();


//                try {
//                    itemsOnClick = null;
//                    birthdayPopupWindow = new BirthdayPopupWindow(WoDeZiLiaoActivity.this, (View.OnClickListener) itemsOnClick);
//                    birthdayPopupWindow.showAtLocation(findViewById(R.id.relative_ziliao), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//
//                    birthdayPopupWindow.setBirthdayClick(new BirthdayPopupWindow.BirthdayClick() {
//                        @Override
//                        public void birthdayclick(int year, int month, int day) {
//                            tvXuanzeShengri.setText(year+"-"+month+"-"+day);
//                        }
//                    });
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                break;
//            、保存
            case R.id.btn_save:

                Calendar instance = Calendar.getInstance();

                int year = instance.get(Calendar.YEAR);
                int month = instance.get(Calendar.MONTH) + 1;// 获取当前月份
                int day = instance.get(Calendar.DAY_OF_MONTH);// 获取当日期
//                int hour = instance.get(Calendar.HOUR_OF_DAY);
//                int minute = instance.get(Calendar.MINUTE);
                System.out.println(month + "      month");
                System.out.println(day + "      day");
//                System.out.println(hour+"       hour");
//                System.out.println(minute+"         minute");
                System.out.println(tvXuanzeShengri.getText().toString().trim() + "         tvXuanzeShengri");


                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date = sdf.parse(tvXuanzeShengri.getText().toString().trim());
                    System.out.println(date + "    date");
                    System.out.println(date.getTime() + "            date.getTime()");
                    Date date1 = sdf.parse(year + "-" + month + "-" + day);
                    System.out.println(year + "-" + month + "-" + day + "         生日生日生日");

                    if (date.getTime() > date1.getTime()) {
                        Toast.makeText(this, "请输入正确的生日！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }


//                if(photoEntity == null){
//                    Toast.makeText(this, "请上传头像", Toast.LENGTH_SHORT).show();
//                }else
                if (etName.getText().toString().equals("")) {
                    Toast.makeText(this, "请填写昵称", Toast.LENGTH_SHORT).show();
                } else if (sex.equals("")) {
                    Toast.makeText(this, "请选择性别", Toast.LENGTH_SHORT).show();
                } else if (tvXuanzeShengri.getText().toString().equals("")) {
                    Toast.makeText(this, "请选择生日", Toast.LENGTH_SHORT).show();
                } else {
////                                    编辑个人信息的网络请求
                    initBianJiXinXiHttp();
                }
                break;
        }
    }


    /*

* 将时间转换为时间戳
*/
    public static String dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts / 1000);
        return res;
    }


    //    编辑个人信息的网络请求
    private void initBianJiXinXiHttp() {

        String birth = "";
        try {
            birth = dateToStamp(tvXuanzeShengri.getText().toString().trim());
            System.out.println(birth + "         时间戳");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println(tvXuanzeShengri.getText().toString().trim() + "         11111111111111");

        String imageURl = "";
        if (photoEntity == null) {
            if (userEntity.getResponse().getAvatar() != null) {
                imageURl = userEntity.getResponse().getAvatar();
            }
        } else {
            imageURl = photoEntity.getResponse().getFileurl();
        }


        System.out.println(imageURl + "               imageURl");
        System.out.println(etName.getText().toString().trim() + "         name");
        System.out.println(sex + "       ssexx");
        System.out.println(tvXuanzeShengri.getText().toString().trim() + "           birth");

        final ProgressDialog progressDialog = new ProgressDialog(WoDeZiLiaoActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "user/editUinfo")
                .addHeader("token", ContractUtils.getTOKEN(WoDeZiLiaoActivity.this))
                .addParams("avatar", imageURl)
                .addParams("nickname", etName.getText().toString().trim())
                .addParams("sex", sex)
                .addParams("birth", birth)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e + "      eeeee编辑个人信息");
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(WoDeZiLiaoActivity.this, response);
                        System.out.println(response + "          编辑个人信息的网络请求");

                        progressDialog.dismiss();
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            XiuGaiEntity xiuGaiEntity = gson.fromJson(response, XiuGaiEntity.class);
                            Toast.makeText(WoDeZiLiaoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.putExtra("touxiang", xiuGaiEntity.getRequest().getAvatar());
                            intent.putExtra("name", xiuGaiEntity.getRequest().getNickname());
                            intent.putExtra("sex", xiuGaiEntity.getRequest().getSex());
                            intent.putExtra("shengri", xiuGaiEntity.getRequest().getBirth());
                            intent.setAction("xiugai");
                            sendBroadcast(intent);
                            finish();
                        }
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && photoUri != null) {
            String string = photoUri.toString();

            File file = new File(string);
            System.out.println(file.exists() + "      file");
            if (file.exists() == false) {
                return;
            }
            setHeadImage(string);
//            image_touxiang.setImageURI(Uri.parse(string));
            uploadFile1(string);

        }


        if (data != null && requestCode == 1) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (images != null) {
                setHeadImage(images.get(0).path);
//                image_touxiang.setImageURI(Uri.parse(images.get(0).path));
                uploadFile(images.get(0));
            } else {
                Toast.makeText(this, "图片解析失败", Toast.LENGTH_SHORT).show();
            }
        } else {
//            Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
        }
    }


    private void uploadFile(ImageItem imageItem) {
        final ProgressDialog progressDialog = new ProgressDialog(WoDeZiLiaoActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        File file = new File(imageItem.path);
        Luban.with(this)
                .load(file)
                .ignoreBy(100)
                //  .setTargetDir(AppConfig.DEFAULT_SAVE_IMAGE_PATH)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
//                        String url = ContractUtils.LOGIN_URL+"ceshi/ce_upload.html";
                        OkHttpClient okHttpClient = new OkHttpClient();
//                        RequestBody requestBody1 =new FormBody.Builder()
//                                .add("driverid",substring)
//                                .add("driver_img_type","1")
//                                .build();
                        RequestBody requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                                .build();

                        Request request = new Request.Builder()
                                .url(ContractUtils.LOGIN_URL + "index/upload")
                                .addHeader("token", ContractUtils.getTOKEN(WoDeZiLiaoActivity.this))
                                .post(requestBody)
                                .build();

                        okHttpClient.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

//                                        Toast.makeText(WoDeZiLiaoActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(Call call, final Response response) throws IOException {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(WoDeZiLiaoActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                    }
                                });


                                progressDialog.dismiss();
                                String string = response.body().string();
                                Gson gson = new Gson();
                                photoEntity = gson.fromJson(string, PhotoEntity.class);

                                System.out.println(string + "     我的资料上传头像");
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }


    private void uploadFile1(String imageItem) {
        final ProgressDialog progressDialog = new ProgressDialog(WoDeZiLiaoActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        File file = new File(imageItem);
        Luban.with(this)
                .load(file)
                .ignoreBy(100)
                //  .setTargetDir(AppConfig.DEFAULT_SAVE_IMAGE_PATH)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        RequestBody requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                                .build();

                        Request request = new Request.Builder()
                                .url(ContractUtils.LOGIN_URL + "index/upload")
                                .addHeader("token", ContractUtils.getTOKEN(WoDeZiLiaoActivity.this))
                                .post(requestBody)
                                .build();

                        okHttpClient.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
//                                        Toast.makeText(WoDeZiLiaoActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                progressDialog.dismiss();
                            }


                            @Override
                            public void onResponse(Call call, final Response response) throws IOException {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(WoDeZiLiaoActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                    }
                                });


                                progressDialog.dismiss();
                                String string = response.body().string();
                                Gson gson = new Gson();
                                photoEntity = gson.fromJson(string, PhotoEntity.class);

                                System.out.println(string + "     我的资料上传头像");
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (permissions.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                        //创建文件夹 在本地文件Pictures 目录下创建 自己得文件夹
                        File dir = new File(Environment.getExternalStorageDirectory() + "/Pictures/image");
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        //照片名称
                        File file = new File(dir, new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
                        photoUri = Uri.parse(file.getPath());

                        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                                .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), 100);

                    } else {
//                                    showToast("请检查SDCard！");
                    }
                } else {
//                    Toast.makeText(WoDeZiLiaoActivity.this, "", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }


}
